package com.yanyu.space.common.log.handler;

import com.yanyu.space.common.log.MDCHelper;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Closeable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yanyu
 */
@Data
@NoArgsConstructor
public class LogWorkerContext implements Closeable {

    private String traceId;
    private LogWorker logWorker;
    /**
     * 线程进入数
     */
    private final AtomicInteger threadCunter = new AtomicInteger(1);

    public LogWorkerContext(String traceId, LogWorker logWorker) {
        this.traceId = traceId;
        this.logWorker = logWorker;
        MDCHelper.put();
    }

    public Integer decAndGet() {
        MDCHelper.remove();
        return this.threadCunter.decrementAndGet();
    }

    public Integer incAndGet() {
        MDCHelper.put();
        return this.threadCunter.incrementAndGet();
    }

    @Override
    public void close() {
        MDCHelper.remove();
        LogFactory.getInstance().close();
    }
}
